﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RooHui.Infrastructure.Entities.Entity;
using RooHui.Infrastructure.Entities.EFContext;
using RooHui.Tool;
using RooHui.Infrastructure.Entities.Enum;
using RooHui.Infrastructure.Entities.Repository;

namespace RooHui.OA.Biz
{
    public class MemberBiz
    {
        #region 会员相关
        
        public static List<Member> GetMemberByPage(int page, int pageSize, string keyword, 
           int memberType,int activeStatus, ref int count)
        {
            try
            {
                bool isActive=activeStatus==1?true:false;
                using (Context ctx = new Context())
                { 
                    var expression = from c in ctx.Member
                                     where ((c.UserName.Contains(keyword) || c.UserName == null) || (c.RealName.Contains(keyword) || c.RealName == null))
                                     && (c.IDCardNo.Contains(keyword) || c.IDCardNo == null) && (c.Email.Contains(keyword) || c.Email == null)
                                     && (c.MemberType == memberType || memberType == -1)
                                     && (c.IsActive == isActive || activeStatus == -1)
                                     && (c.MemberType==(int)MemberType.Borrower||c.MemberType==(int)MemberType.Invester)
                                     orderby c.UserName
                                     select c;

                    count = expression.Count();
                    var data = expression
                        .Skip((page - 1) * pageSize)
                        .Take(pageSize)
                        .ToList().Select(u => new Member().Set(u)).ToList();
                    return data;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        public static Member ChangeStatus(string userName, int status)
        {
            try
            {
                var member = new Member().Find(c => c.UserName == userName);
                member.Status = (ItemStatus)status;
                member = member.PostModify();
                return member;
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        public static Member GetMemberByUserName(string userName)
        {
            try
            {
                var member = new Member().Find(c => c.UserName == userName);
                
                return member;
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

       

        #endregion
        #region 经纪人相关
        public static List<Member> GetAgentByPage(int page, int pageSize, string keyword, ref int count)
        {
            try
            {

                using (Context ctx = new Context())
                {
                    var expression = from c in ctx.Member
                                     join d in ctx.AgentInfo
                                     on c.UserName equals d.UserName
                                     where ((c.UserName.Contains(keyword) || c.UserName == null) || (c.RealName.Contains(keyword) || c.RealName == null))
                                     && (c.IDCardNo.Contains(keyword) || c.IDCardNo == null) && (c.Email.Contains(keyword) || c.Email == null)
                                     && c.MemberType == (int)MemberType.Agent
                                     orderby c.UserName
                                     select new{c,d};

                    count = expression.Count();
                    var data = expression
                        .Skip((page - 1) * pageSize)
                        .Take(pageSize)
                        .ToList().Select(u => new Member().Set(u.c).LoadAgentInfo(u.d)).ToList();
                    return data;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        public static Member AddAgent(string userName, string realName, string idCardNo, string handPhone, string address, string createUser, Gender gender, int settlementType, decimal settlement)
        {
            try
            {
                var member = new Member();
                member.Address = address;
                member.CreateTime = DateTime.Now;
                member.CreateType = CreateType.Mortgagor;
                member.CreateUser = createUser;
                member.Email = userName;
                member.EmailCheck = true;
                member.Gender = gender;
                member.HandPhone = handPhone;
                member.HandPhoneCheck = true;
                member.IDCardNo = idCardNo;
                member.IDCardCheck = true;
                member.IsActive = true;
                member.MemberType = MemberType.Agent;
                member.Password = AesAlgorithm.Encrypt(userName);
                member.RealName = realName;
                member.Status = ItemStatus.Enable;
                member.UserName = userName;
                member = member.PostAdd();
                if (member != null)
                {
                    var agent = new AgentInfo();
                    agent.UserName = userName;
                    agent.AgentCode = SupportBiz.RandomCode(idCardNo.Remove(2));
                    agent.SettlementType = (SettlementType)settlementType;
                    agent.Settlement = settlement;
                    agent.PostAdd();
                    return member;
                }
                else
                {
                    return null;
                }
                
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        public static Member EditAgent(string userName, string realName, string idCardNo, string handPhone, string address, Gender gender, int settlementType, decimal settlement)
        {
            try
            {
                var member = new Member().Find(userName);
                member.RealName = realName; 
                member.HandPhone = handPhone;
                member.IDCardNo = idCardNo;
                member.Gender = gender;
                member.Address = address; 
                member = member.PostModify();

                var agent = new AgentInfo().Find(userName);
                
                agent.SettlementType = (SettlementType)settlementType;
                agent.Settlement = settlement;
                agent.PostModify();

                return member;
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        public static Member DeleteAgent(string userName)
        {
            try
            {
                var member = new Member().Find(userName);
                member.Status = ItemStatus.Delete;
                member = member.PostModify();
                UserRoleBiz.UserAuthorizeDelete(userName);
                return member;
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        public static Member ChangeAgentStatus(string userName, int status)
        {
            try
            {
                var member = new Member().Find(userName);
                member.Status = (ItemStatus)status;
                member = member.PostModify();
                return member;
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }
        public static bool AgentExsit(string userName)
        {
            bool isTrue = false;
            try
            {
                var user = new User().Find(c => c.UserName == userName);
                if (user != null)
                {
                    isTrue = true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return isTrue;
        }

        public static Member GetAgentByUserName(string userName)
        {
            try
            {
                using (Context ctx = new Context())
                {
                    var member = (from c in ctx.Member
                                  join d in ctx.AgentInfo
                                  on c.UserName equals d.UserName
                                  where c.UserName == userName
                                  select new { c, d })
                               .ToList()
                               .Select(m => new Member().Set(m.c).LoadAgentInfo(m.d)).FirstOrDefault();
                    return member;   
                }
                
                
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        public static List<AgentProfitStream> GetAgentProfitListByPage(int page, int pageSize, DateTime startDate, DateTime endDate,string agentUserName, ref int count,int type=-1)
        {
            try
            {
                endDate = endDate.AddDays(1);
                using (Context ctx = new Context())
                {
                    var expression = from c in ctx.AgentProfitStream
                                     join e in ctx.Member
                                     on c.Invester equals e.UserName into et
                                     from ei in et.DefaultIfEmpty()
                                     join f in ctx.Investment
                                     on c.InvestmentId equals f.ID into ft
                                     from fi in ft.DefaultIfEmpty()
                                     join h in ctx.Project
                                     on fi.ProjectId equals h.ID into ht
                                     from hi in ht.DefaultIfEmpty()
                                     where (c.RecordDate>=startDate&&c.RecordDate<endDate) &&(c.Type==type||type==-1)
                                     &&c.UserName==agentUserName
                                     orderby c.RecordDate descending
                                     select new { c, ei,fi,hi };

                    count = expression.Count();
                    var data = expression
                        .Skip((page - 1) * pageSize)
                        .Take(pageSize)
                        .ToList().Select(u => new AgentProfitStream().Set(u.c).LoadInvesterUser(u.ei).LoadInvestment(u.fi,u.hi)).ToList();
                    return data;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }

        #endregion

        public static Member GetMemeberDetail(string userName)
        {
            try
            {
                using (Context ctx = new Context())
                {
                    var data = (from c in ctx.Member
                                join d in ctx.AgentInfo
                                on c.UserName equals d.UserName into dt
                                from di in dt.DefaultIfEmpty()
                                join e in ctx.Account
                                on c.UserName equals e.UserName into et
                                from ei in et.DefaultIfEmpty()
                                join f in ctx.User
                                on c.CreateUser equals f.UserName into ft
                                from fi in ft.DefaultIfEmpty()
                                where c.UserName == userName
                                select new { c, di, ei,fi })
                                     .ToList()
                                     .Select(m => new Member().Set(m.c).LoadAccount(m.ei).LoadAgentInfo(m.di).LoadUser(new U_User() { RealName = m.fi == null ? "" : m.fi.RealName })).FirstOrDefault();
                     return data;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return null;
        }
    }
}
